import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity,
  PixelRatio, Image, FlatList, TextInput
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { API, API_GENERATE } from '../../../../config/api';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import WarningService from '../../../warning/_common/service';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import HTTP from '../../../../utils/http'
import Dictionary from '../../../../utils/dictionary';
import ToastUtil from '../../../../utils/toast';

const arrowIcon = require('../../../../imgs/sanjiao3.png');
const scale = GLOBAL.SCALE;

export class ApproveApplyList extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '付款申请审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };
  constructor(props) {
    super(props);
    this.params = this.props.navigation.state.params;
    let { choice } = this.params || {};
    this.state = {
      status: 'data',
      refreshIcon: false,
      tabIndex: 0,
      tabItem: 0,
      listData: [],
      options: [],
      choice: choice || {},
      itemData: {},
      // isApply:false,
      choiceArr: [
      ],
      listDatas: [],
      modalVisible: false, // 付款类型顶部下拉
      companyData: [{ dictName: '全部', dictKey: null }],
    }
    this.totalPage = 1;
    this.reload = true;
    this.pageParams = { // TODO
      pageNo: 1,
      pageSize: 10,
      paymentApplySource: '',
      corpId: null,
      corpIdList: [],
    }
    this.headIndex = 0;
    this.department = null;//部门条件
  }

  async componentWillMount() {

    await this._initCorpiInit();
    await this.getDictList();
    // await this._initCount();
    await this._initPage();
  }

  //账套初始化 
  _initCorpiInit = async () => {
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    this.choiceArr = userInfo.corpInfoTOs || [];
    let aryyId = [];
    this.choiceArr.forEach((item) => {
      aryyId.push(item.corpId);
    });
    // this.pageParams.corpIdList = aryyId;
    // this.pageParams.corpId = this.choiceArr[0].corpId;
    this.setState({
      choiceArr: this.choiceArr
    })
  }
  // 统计数值 PAY_APPLY_AUDITCOUNT
  // _initCount = async () => {
  //   // this.setState({
  //   //   status: this.reload ? 'loading' : 'data',
  //   // })
  //   let resCount = await HTTP.POST(API_GENERATE(API.PAY_APPLY_AUDITCOUNT))
  //   if (resCount) {
  //     resCount.forEach(item => {
  //       this.choiceArr.forEach((items, index) => {
  //         if (items.corpId == item.corpId) {
  //           this.choiceArr[index].count = item.rowCount;
  //         }
  //       })
  //     })
  //     // this.setState({
  //     //   refreshIcon: false
  //     // })
  //   } else {
  //     this.setState({
  //       // refreshIcon: false,
  //       status: 'error'
  //     })
  //   }
  // }
  // 获取数据字典
  getDictList = async () => {
    let { choice, companyData, tabIndex } = this.state || {};
    let { corpId } = choice || {};
    this.dictionaryData = await Dictionary.get('FIN_PAYMENT_APPLY_SOURCE') || [];
    this.dictionaryData && this.dictionaryData.forEach((element) => {
      companyData.push({ dictKey: element.dictKey, dictName: element.dictName })
    });
    //初始化清空
    this.headIndex = 0;
    this.department = null;

    this.setState({
      companyData: companyData
    })
  }

  // 初始化数据
  _initPage = async () => {
    let { tabIndex } = this.state
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    // console.log(this.pageParams, '--this.pageParams--', this.dictionaryData)
    let res = await HTTP.POST(API_GENERATE(API.PAY_APPLY_AUDITLIST), this.pageParams)
    // 账套参数
    // if (res && res.length) {
    //   res.forEach(item => {
    //     this.choiceArr.forEach((items, index) => {
    //       if (items.corpId == item.corpId) {
    //         this.choiceArr[index].count = item.paginationModel.recordCount;
    //       }
    //     })
    //   })
    // }
    if (res) {
      console.log(res, '99888')
      let resData = res[tabIndex] ? res[tabIndex].paginationModel : '';
      this.totalPage = resData.totalPage;
      this.setState({
        status: resData && resData.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? resData.rows : this.state.listData.concat(resData.rows),
        listDatas: res,
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  // 刷新页面
  _onErrorRefresh = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this._initPage();
  }

  // 下拉刷新
  refresh = () => {
    this.totalPage = 1;
    this.pageParams.pageNo = 1;
    this.reload = false;
    this._initPage();
  }

  // 上拉翻页
  loadMore() {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this._initPage();
    }
  }
  // 账套切换
  changeTab = (index) => {
    this.reload = true;
    this.setState({
      tabIndex: index
    }, () => {
      // this.pageParams.corpId = this.choiceArr[index].corpId;
      this.pageParams.pageNo = 1;
      this.reload = false;
      this._initPage()
    })
  }
  _tabList = (items, i) => {
    this.reload = true;
    this.setState({
      tabItem: i
    }, () => {
      this._initPage()
    })
  }

  // 审批
  approve = async () => {
    const { itemData, choice } = this.state;
    // if (this.requesting) return;
    this.setState({ showRejectModal: false });
    // this.requesting = true;

    let requestParams = {
      businessKey: itemData.paymentApplyInfo.paymentApplyId,
      taskId: itemData.taskId,
      auditResult: this.auditResult,
      remark: this.remark,
      formKey: itemData.formKey,
      corpId: this.pageParams.corpId
    };
    let text = this.auditResult ? '同意' : '驳回';
    this.setState({ status: 'loading' });
    let res = await HTTP.POST(API_GENERATE(API.PAY_APPLY_APPROVEL), requestParams);
    // this.requesting = false;
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        // this._initCount();
        this.refresh();
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }
  // 跳详情
  GoDetails = (item, itemDatas) => {
    // console.log(itemDatas, '998', this.pageParams.corpId)
    this.props.navigation.navigate('ApproveApplyPage', {
      paymentApplyId: item.paymentApplyId,
      businessKey: itemDatas.businessKey,
      taskId: itemDatas.taskId,
      formKey: itemDatas.formKey,
      corpId: this.pageParams.corpId,
      paymentApplySource: item.paymentApplySource
    })
  }
  // 下拉
  _showVisible = () => {
    if (this.state.modalVisible) {
      this.setState({
        modalVisible: false
      })
    } else {
      this.setState({
        modalVisible: true
      })
    }
  }
  _itemFn = (index) => {
    let { companyData } = this.state || {};
    this.headIndex = index;
    this.department = companyData[index].dictName;
    this.pageParams.paymentApplySource = companyData[index]['dictKey'];
    this.state.status = 'loading';
    this.setState({
      modalVisible: false
    }, () => {
      this._initPage();
    })
  }

  _closeModal = () => {
    this.setState({ modalVisible: false });
  }

  _renderListItem = (data) => {
    let item = data.item ? data.item.paymentApplyInfo : {};
    if (!item) return null;
    return (
      <View>
        <TouchableOpacity onPress={() => { this.GoDetails(item, data.item) }}>
          <View style={styles.flexTime}>
            <Text style={styles.flexTimeName}>{item.companyName || '--'}</Text>
            <Text style={styles.flexTimeText}>{item.createTime || '--'}</Text>
          </View>
          <View style={styles.listItem}>
            <View style={styles.flexBoxName}>
              <Text style={styles.flexCompanyName}>{item.paymentApplyCode || '--'}</Text>
              <Image source={arrowIcon} style={styles.arrowIcon} />
            </View>
            <View style={styles.itemBorder}></View>
            <View style={styles.flexNum}>
              <View style={styles.flexApplyText}>
                <Text style={styles.flexApply}>申请来源</Text>
                <Text style={styles.flexOrder}>{item.paymentApplySourceName || '--'}</Text>
              </View>
              <View style={styles.flexApplyText}>
                <Text style={styles.flexApply}>申请金额</Text>
                <Text style={styles.flexOrder}>{(item.paymentApplyAmount || '0').toFixed(2)}{item.currencyName || '元'}</Text>
              </View>
              <View style={styles.flexApplyText}>
                <Text style={styles.flexApply}>计划付款日</Text>
                <Text style={styles.flexOrder}>{item.planPayDate || '--'}</Text>
              </View>
            </View>
            <View style={styles.flexBoxApply}>
              <View style={styles.flexApplyName}><Text style={styles.flexVaule}>申请人</Text></View>
              <View style={[styles.flexApplyName, styles.flexListNull]}>
                <Text>
                  {item.staffName || item.bizTeamName || item.organName ? `${item.staffName || '--'} | ${item.bizTeamName || '--'} | ${item.organName || '--'}` : '--'}
                </Text>
              </View>
            </View>
            <View style={styles.itemBorder}></View>
            <View style={styles.itemDayTime}>
              <Text style={[styles.consent, styles.consentColor]} onPress={() => {
                this.auditResult = 1;
                this.remark = '';
                this.setState({
                  showRejectModal: true,
                  itemData: data.item,
                })
                // this.consentCreate(item)
              }}>同意</Text>
              <Text style={styles.itemdown} onPress={() => {
                if (item) {
                  this.auditResult = 0;
                  this.remark = '';
                  this.setState({
                    showRejectModal: true,
                    itemData: data.item,
                  })
                } else {
                  ToastUtil.showWarning('没有数据')
                }
              }}>驳回</Text>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  render() {
    let { choiceArr, listDatas, listData, status, refreshIcon, showRejectModal, tabItem, tabIndex, modalVisible, companyData } = this.state;
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
          this._initPage();
        }} />
        <View style={styles.flexBox}>
          {listDatas && listDatas.length > 1 ? (
            <View style={styles.tabWrap}>
              {
                listDatas && listDatas.map((item, index) => {
                  return (
                    <TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
                      <Text style={[styles.tabText, tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.corpName} {item.paginationModel.recordCount || '0'}</Text>
                    </TouchableOpacity>
                  )
                })
              }
            </View>
          ) : <View style={{ flexDirection: 'row', height: 20 * scale, backgroundColor: style.color.themeColor }}></View>
          }
        </View>

        <View style={styles.listBox}>
          <View style={styles.listScreen}>
            <TouchableOpacity onPress={this._showVisible} style={styles.flexRow}>
              <Text style={styles.allBtn}>{this.department || '全部'}</Text>
              <Image source={require('../../../../imgs/select.png')} />
            </TouchableOpacity>
          </View>
        </View>
        {/* <View style={[styles.stateView]}>
          {
            this.itemDataList && this.itemDataList.map((items, index) => {
              return (
                <TouchableOpacity key={index} style={[styles.stateItem, tabItem == index ? styles.stateItemActive : null]} onPress={() => { this._tabList(items, index) }}>
                  <Text style={[styles.stateItemText, tabItem == index ? styles.stateItemTextActive : null]}>{items.dictName}</Text>
                </TouchableOpacity>
              )
            })
          }
        </View> */}
        {
          status == 'data' ? (
            <View style={{ flex: 1, paddingBottom: 10 * scale, }}>
              <FlatList
                data={listData}
                style={{ marginLeft: 12 * scale, marginRight: 12 * scale }}
                renderItem={this._renderListItem}
                refreshing={refreshIcon}
                onRefresh={() => { this.refresh() }}
                onEndReachedThreshold={0.1}
                onEndReached={() => { this.loadMore() }}
              />
            </View>
          ) : null
        }
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无数据'} onErrorPress={this._onErrorRefresh} />) : null
        }
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={this.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.remark = text;
            this.approve();
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={this.headIndex} title={'请选择授权部门'} listData={companyData || []} selectCallBack={this._itemFn} />
        )} isVisible={modalVisible} closeCallballFn={this._closeModal} />
      </View >
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
    paddingBottom: 30 * scale
  },
  flexBox: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    backgroundColor: style.color.themeColor,
    paddingLeft: 50 * scale,
  },
  tabWrap: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  tabItem: {
    paddingLeft: 36 * scale,
    paddingRight: 36 * scale,
    paddingBottom: 12 * scale,
  },
  tabText: {
    color: '#ffffff',
    // textAlign: 'center'
  },
  listBox: {
    // flex: 1,
  },
  listScreen: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 60 * scale,
    paddingLeft: 20 * scale,
    paddingRight: 20 * scale
  },
  flexRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  allBtn: {
    color: '#0E7FFD',
    fontWeight: 'bold',
    marginRight: 10 * scale
  },
  stateView: {
    flexDirection: 'row',
    marginTop: 15 * scale,
    flexWrap: 'wrap',
    marginLeft: 20 * scale,
  },
  stateItem: {
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    marginBottom: 15 * scale,
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemText: {
    paddingRight: 4 * scale,
    paddingLeft: 4 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemInfo: {
    width: 6 * scale,
    height: 6 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItemInfoActive: {
    backgroundColor: style.color.white
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  flexTime: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingRight: 20 * scale,
    marginTop: 5 * scale,
    paddingLeft: 8 * scale,
  },
  flexTimeName: {
    fontSize: 12 * scale,
    color: '#000',
    fontWeight: '700',
    width: 180 * scale,
  },
  flexTimeText: {
    fontSize: 12 * scale,
    color: '#000',
    opacity: 0.6,
  },
  listItem: {
    backgroundColor: '#fff',
    borderRadius: 4 * scale,
    marginBottom: 22 * scale,
    marginTop: 8 * scale,
  },
  arrowIcon: {
    width: 8 * scale,
    height: 12 * scale,
    position: 'absolute',
    right: 0,
    top: 8 * scale,
    right: 20 * scale,
  },
  flexBoxName: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 8 * scale,
    paddingBottom: 13 * scale,
  },
  flexCompanyName: {
    paddingLeft: 17 * scale,
    fontSize: 12 * scale,
    color: '#000',
    // opacity: 0.9,
    // fontWeight: '500',
  },
  flexNum: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingLeft: 24 * scale,
    paddingRight: 10 * scale,
    paddingBottom: 12 * scale,
  },
  itemBorder: {
    height: 1 * scale,
    backgroundColor: '#E3E7F0',
    marginBottom: 15 * scale,
  },
  flexApplyText: {
    marginLeft: 10 * scale,
  },
  flexApply: {
    color: '#000',
    fontSize: 12 * scale,
    opacity: 0.6,
  },
  flexOrder: {
    flexDirection: 'row',
    width: 115 * scale,
    color: '#000',
    fontSize: 13 * scale,
    marginTop: 5 * scale,
    fontWeight: '700',
    paddingRight: 10 * scale,
  },
  flexBoxApply: {
    // flexDirection: 'row',
    paddingBottom: 33 * scale,
  },
  flexApplyName: {
    flexDirection: 'row',
    paddingLeft: 24 * scale,
  },
  flexVaule: {
    fontSize: 12 * scale,
    color: '#000',
    opacity: 0.9,
  },
  flexListNull: {
    marginTop: 5 * scale,
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row',
    paddingBottom: 16 * scale,
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  consentColor: {
    // backgroundColor: style.color.themeColor,
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
})